import copy
import random

import yaml
import os
import logging
from log import mns_log

mns_log.Log.mns_logging()


class Parse:
    setting = {}
    host_conf = {}
    ship_conf = {}
    world_conf = {}

    @classmethod
    def parse_config(cls, config_path):
        """解析配置文件"""
        logging.info("正在解析配置文件")
        if os.path.exists(config_path):
            with open(config_path, "r", encoding = "utf8") as file:
                config = yaml.safe_load(file)
                cls.world_conf = config["world"]
                cls.ship_conf = config["ship"]
                cls.host_conf = config["host"]
                cls.setting = config["setting"]
        else:
            logging.error("该文件不存在")

    @classmethod
    def get_world_name(cls):
        world_name = cls.world_conf["name"]
        return world_name

    @classmethod
    def get_world_size(cls):
        world_size = cls.world_conf["size"]
        size = world_size.split(",")
        return float(size[0]) * 1000, float(size[1]) * 1000

    @classmethod
    def get_ship_group_count(cls):
        ship_group_num = cls.ship_conf["group"]
        return int(ship_group_num)

    @classmethod
    def get_ship_count(cls):
        """获得船只总数"""
        group_count = cls.get_ship_group_count()
        ship_count = 0
        for i in range(group_count):
            ship_count += cls.get_ship_count_in_group(i)
        return ship_count

    @classmethod
    def get_ship_count_in_group(cls, index: int):
        """获得该组船只数量"""
        return int(cls.ship_conf["group" + str(index)]["number"])

    @classmethod
    def get_ship_course_in_group(cls, index: int):
        """获得该组船只航行方向（角度）"""
        return int(cls.ship_conf["group" + str(index)]["course"])

    @classmethod
    def get_ship_speed_in_group(cls, index: int):
        """获得该组船只航行速度"""
        speed_round = str(cls.ship_conf["group" + str(index)]["speed"])
        if "," in speed_round:
            min_speed, max_speed = speed_round.split(",")
        else:
            min_speed, max_speed = speed_round, speed_round
        return int(min_speed), int(max_speed)

    @classmethod
    def get_ship_pos_in_group(cls, index: int):
        """获得该组船只中心位置"""
        pos = str(cls.ship_conf["group" + str(index)]["position"]).split(",")
        return float(pos[0]), float(pos[1])

    @classmethod
    def get_host_by_ship_group(cls, index: int):
        """获得该组船只节点配置"""
        host_group = cls.ship_conf["group" + str(index)]["host"]
        host_conf = cls.host_conf["group" + host_group[4:]]
        return host_conf

    @classmethod
    def get_single_host_by_ship_group(cls, index: int):
        """通过host id，获得单个host的配置"""
        return cls.handler_host_config(cls.host_conf["group" + str(index)])

    @classmethod
    def handler_host_config(cls, config: dict):
        my_conf = copy.deepcopy(config)
        for key, value in my_conf.items():
            if "," in str(value):
                v = str(value).split(",")
                new_val = random.randint(int(v[0]), int(v[1]))
                if key == "send_round":
                    step_size = cls.get_sim_step()
                    new_val = int(new_val / step_size) * step_size
                my_conf[key] = new_val
        return my_conf

    @classmethod
    def get_host_num_by_ship_group(cls, index: int):
        """获得该组船只节点组号码"""
        host_group = cls.ship_conf["group" + str(index)]["host"]
        if "host" in host_group:
            return int(host_group[4:])
        else:
            return int(host_group)

    @classmethod
    def get_router_by_ship_group(cls, index: int):
        """获得该组船只路由协议"""
        protocol = cls.get_host_by_ship_group(index)["protocol"]
        if protocol == "default":
            protocol = "router"
        return protocol.capitalize()

    @classmethod
    def get_queen_length_by_ship_group(cls, index: int):
        """获得该组船只路由协议"""
        len = cls.get_host_by_ship_group(index + 1)["queen_length"]
        if len:
            return int(len)
        else:
            return 512

    @classmethod
    def get_sim_step(cls):
        """获得仿真步长"""
        return float(cls.setting["step_size"]) * 1000

    @classmethod
    def get_sim_start_time(cls):
        """获得仿真开始时间"""
        return float(cls.setting["start_time"]) * 1000

    @classmethod
    def get_sim_finish_time(cls):
        """获得仿真结束时间"""
        return float(cls.setting["end_time"]) * 1000

    @classmethod
    def get_holle_round(cls):
        """获得发现邻居节点间隔时间 ms"""
        return float(cls.setting["hello_round"]) * 1000

    @classmethod
    def get_communication_distance(cls):
        """获得节点最大通信距离"""
        return float(cls.setting["communication_distance"])


if __name__ == "__main__":
    Parse.parse_config("default_config.yaml")
    print(Parse.get_sim_step())
